package com.star.percalservice.utils;

import com.star.percalservice.mapper.UserMapper;
import com.star.percalservice.model.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CheckTokenAndGetUserUtil {

    @Autowired
    private UserMapper userMapper;

    /**
     * 校验token
     * @param request
     * @return
     */
    public boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        // 空校验
        if (token == null || token.isEmpty()) {
            return false;
        }

        // 过期校验
        if (JwtTokenUtils.isTokenExpired(token)) {
            return false;
        }

        // 失效校验
        return JwtTokenUtils.validateToken(token);
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    public User getUserByToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long uid = Long.valueOf(JwtTokenUtils.getUidFromToken(token));
        return userMapper.selectById(uid);
    }

}
